package com.jetsum.micro.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.jetsum.api.service.HelloService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class SentinelDemoController {

    @Reference(loadbalance = "random")
    private HelloService helloService;

    @GetMapping("/say")
    public String say(String name) {
        return helloService.sayHello(name);
    }

    /**
     * url限流测试
     * @param id
     * @return
     */
    @SentinelResource(value = "onlyMessageName",    //资源名称
            blockHandler = "testUrlBlockHandler"    //限流后处理方法名，方法返回参数和方法参数必须一致，可以添加BlockException e参数
    )
    @GetMapping("/testUrl")
    public String testUrl(String id,HttpServletRequest request) {
        return "{id:" + id + "}";
    }

    public String testUrlBlockHandler(String id, BlockException e) {
        return "{id:" + id + "}--->限流了";
    }

    /**
     * 热点参数限流，在dashboard中操作名为"paramLimit--"的资源 可达到在线热点参数限流
     * @param id
     * @param name
     * @return
     */
    @SentinelResource(value = "paramLimit--",fallback = "paramLimitDemoFallback")
    @GetMapping("/paramLimit")
    public String paramLimitDemo(String id, String name) {
        if ("fallback".equals(id)) {
            int i = 1 / 0;
        }
        return "{id:" + id + ",name:" + name + "}";
    }

    public String paramLimitDemoFallback(String id, String name, Throwable t) {
        return "{id:" + id + ",name:" + name + "} 降级";
    }

    @GetMapping("/get/{id}")
    public String get(@PathVariable String id){
        return id;
    }
}
